import React, { useState, useEffect, useCallback } from 'react';
import { Card, Input, Button, Space, Table, Modal } from "antd";
import { SearchOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import {  deleteMerchantInfo, updateMerchantInfo } from "../api/merchant";
import Message from '@/components/Message';
import MerchantForm from '@/pages/merchant/components/MerchantForm';
import "../style/MerchantInfo.css";
import Excel from "../../finance/Excel";
import { state as states } from "@/stores/Merchant"
import { useSnapshot } from 'valtio';
const Merchant: React.FC = () => {
    const [merchantList] = useState<any[]>([]);
    const state = useSnapshot(states);
    const [form, setForm] = useState<any>({
        code: "",
        merchant: "",
        address: "",
        name: "",
        phone: "",
        uploadUrl: ""
    });
    const [merChantName, setMerChantName] = useState<string>("");
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [showMessage, setShowMessage] = useState<boolean>(false);
    const [selectedMerchant, setSelectedMerchant] = useState<any>(null);

    // 获取商户信息
    const fetchMerchants = useCallback(async () => {
        await state.getData({ merChantName });
    }, [merChantName]);

    useEffect(() => {
        states.getData({});
    }, []);

    // 搜索商户
    const handleSearch = () => {
        fetchMerchants()
    };

    // 修改商户信息
    const handleUpdate = () => {
        updateMerchantInfo(form).then(async () => {
            // if (res.code === 200) {
            await fetchMerchants()
            setModalOpen(false);
            // }
        });
    };

    // 删除商户信息
    const handleDelete = () => {
        if (selectedMerchant) {
            deleteMerchantInfo(selectedMerchant).then((res: any) => {
                if (res.code === 200) {
                    fetchMerchants();
                    setShowMessage(false);
                }
            });
        }
    };

    const columns: TableProps<any>['columns'] = [
        { title: "序号", dataIndex: 'key', key: 'key' },
        { title: "商户名称", dataIndex: 'merchant', key: 'merchant' },
        { title: "地址", dataIndex: 'address', key: 'address' },
        { title: "联系人", dataIndex: 'name', key: 'name' },
        { title: "手机号", dataIndex: 'phone', key: 'phone' },
        {
            title: "操作",
            render: (_, record) => (
                <Space size="middle">
                    <a onClick={() => {
                        setForm(record);
                        setModalOpen(true);
                    }}>编辑</a>
                    <a className='color-red' onClick={() => {
                        setSelectedMerchant(record);
                        setShowMessage(true);
                    }}>注销</a>
                </Space>
            ),
        }
    ];

    const messageInfo = {
        headTitle: "商户注销提示",
        bodyTitle: `请确认是否注销商户[${selectedMerchant?.merchant || ''}]！`,
        bodyContent: "注销后商户将无法使用，请谨慎操作！",
    };

    return (
        <div className='m=auto w-[100%] m-t-5'>
            <Message
                setShow={setShowMessage}
                show={showMessage}
                callBack={handleDelete}
                info={messageInfo}
            />
            <Card title='商户筛选' className='m-auto w-[90%] rounded-none p-0'>
                <div style={{ display: "flex", height: "30px", lineHeight: '30px', padding: 0 }}>
                    <p className='m-0'>商户名称：</p>
                    <Input
                        placeholder="请输入商户名称"
                        className='w-40 rounded-none m-l-2 m-r-10'
                        value={merChantName}
                        onChange={e => setMerChantName(e.target.value)}
                    />
                    <Button
                        type="primary"
                        className='rounded-none'
                        icon={<SearchOutlined />}
                        onClick={handleSearch}
                    >
                        查询
                    </Button>
                </div>
            </Card>
            <Card className='w-[90%] m-auto mt-5 rounded-none'>
                <div className='flex justify-between items-center'>
                    <p>共有{state.merchantList.length}条记录</p>
                    <Button className='rounded-none'>
                        <Excel data={merchantList} fileName="商户列表">导出数据</Excel>
                    </Button>
                </div>
                <Table
                    bordered
                    className='rounded-none'
                    columns={columns}
                    dataSource={states.merchantList}
                    pagination={{
                        defaultPageSize: 5,
                        total: merchantList.length,
                        showSizeChanger: true,
                        pageSizeOptions: ['5', '10', '20'],
                    }}
                />
            </Card>
            <Modal
                style={{ borderRadius: 0 }}
                title="编辑商户信息"
                centered
                open={modalOpen}
                onOk={handleUpdate}
                onCancel={() => setModalOpen(false)}
                footer={[
                    <Button key="back" onClick={() => setModalOpen(false)}>取消</Button>,
                    <Button key="submit" type="primary" onClick={handleUpdate}>确定</Button>,
                ]}
            >
                <MerchantForm form={form} setForm={setForm} />
            </Modal>
        </div>
    );
};

export default Merchant;
